<template>
    <div class="add-video">
        <el-form :model="form" class="my-form" label-width="100px" :disabled="disabled">
            <el-form-item label="配置名称" required>
                <el-input clearable v-model="form.title" style="width: 300px;" maxlength="50" placeholder="输入名称，不会作为通知内容" />
            </el-form-item>
            <el-form-item label="通知标题" required>
                <el-input clearable v-model="form.name" style="width: 300px;" maxlength="50" placeholder="输入标题，作为通知标题" />
            </el-form-item>
            <el-form-item label="触发节点" required>
                <el-select v-model="form.trigger_node" placeholder="请选择触发节点" style="width: 300px;" @change="selecttriggerNode">
                    <el-option :label="item.name" :value="item.id" v-for="(item, index) in triggerNodeList" :key="index" />
                </el-select>
            </el-form-item>
            <el-form-item label="通知内容" required>
                <el-input type="textarea" v-model="form.content" resize="none" :rows="6" placeholder="通知内容建议不超过30字符" style="width: 300px;" />
            </el-form-item>
            <el-form-item label="指定国家" required>
                <el-checkbox class="check-all" v-model="checkAll" :indeterminate="isIndeterminate"
                    @change="selectAllCountry">全部</el-checkbox>
                <el-checkbox-group v-model="form.country_code" @change="selectCountry">
                    <el-checkbox v-for="(item, index) in countryList" :key="index" :label="item.id">{{ item.cn_name
                    }}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <div style="display: flex;">
            <el-form-item label="生效时间" required>
                <el-select v-model="form.effect_type" placeholder="请选择生效时间" style="width: 150px;" @change="selectEffectType">
                    <el-option :label="item.title" :value="item.type" v-for="(item, index) in effectTypeList" :key="index" />
                </el-select>
            </el-form-item>
            <el-form-item label="提交时间" v-if="form.effect_type === 0">
                <el-date-picker v-model="tempForm.selectData" :editable="false" start-placeholder="开始时间" end-placeholder="结束时间"
                type="daterange" range-separator="至" value-format="YYYY-MM-DD" />
            </el-form-item>
            </div>
            <!-- <el-form-item label="指定账号角色" required>
                <el-checkbox class="check-all" v-model="checkRoleAll" :indeterminate="isRoleIndeterminate"
                    @change="selectAllRole">全部</el-checkbox>
                <el-checkbox-group v-model="form.effect_role" @change="selectRole">
                    <el-checkbox v-for="(item, index) in roleList" :key="index" :label="item.id">{{ item.name
                    }}</el-checkbox>
                </el-checkbox-group>
            </el-form-item> -->
        </el-form>
        <el-form-item class="btn-box">
            <el-button @click="back">返回</el-button>
            <el-button type="primary" @click="submitAppConfig" :disabled="disabled">提交</el-button>
        </el-form-item>
    </div>
</template>
  
  <script setup>
  import { reactive, ref, onMounted, watchEffect} from 'vue'
  import { useRouter, useRoute } from 'vue-router';
  import { useTabNar } from '@/stores/tabnar';
  import { useCommonStore } from '@/stores';
  import { getConfigEnum, addConfig, editConfig} from '@/api/operateManage/AppNotifyConfig.js';
  import { ElLoading, ElMessage } from 'element-plus';
  import { isEmpty } from 'lodash-es';
  
  //data
  const router = useRouter()
  const route = useRoute()
  const tabNar = useTabNar()
  const commonStore = useCommonStore()
  const form = reactive({
    name: '',
    country_code: [],
    effect_role: [],
    trigger_node: '',
    id: '',
    content: '',
    title: '',
    effect_type: '',
    effect_start: '',
    effect_end: ''
  })
  const tempForm = reactive({
    selectData: []
  })

  watchEffect(() => {
    
  if (!isEmpty(tempForm.selectData)) {
    form.effect_start = tempForm.selectData[0] + ' 00:00:00'
    form.effect_end = tempForm.selectData[1] + ' 23:59:59'
  } else {
    form.start_time = ''
    form.end_time = ''
  }
})
  const disabled = ref(false);
  const isIndeterminate = ref(true);
  // const isRoleIndeterminate = ref(true);
  const checkAll = ref(false);
  // const checkRoleAll = ref(false);
  const countryList = ref([]);
  const triggerNodeList = ref([]);
  // const roleList = ref([]);
  const isEdit = ref(false);
  const effectTypeList = ref([]);
  
  
  // methods
  const back = () => {
    // 返回上一页
    router.go(-1)
    tabNar.deleteTab(route)
  }
  
  const selectCountry = (val) => {
    form.country_code = val
    const checkedCount = val.length
    checkAll.value = checkedCount === countryList.value.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < countryList.value.length
  }
  
  const selectAllCountry = (val) => {
    form.country_code = val ? countryList.value.map(it => it.id) : []
    isIndeterminate.value = false
  }

  // const selectRole = (val) => {
  //   form.role = val
  //   const checkedCount = val.length
  //   checkRoleAll.value = checkedCount === roleList.value.length
  //   isRoleIndeterminate.value = checkedCount > 0 && checkedCount < roleList.value.length
  // }
  
  // const selectAllRole = (val) => {
  //   form.role = val ? roleList.value.map(it => it.id) : []
  //   isRoleIndeterminate.value = false
  // }
  const selecttriggerNode = (val) => {
    form.trigger_node = val;
  }
  const selectEffectType = (val) => {
    if (val === 1) {
        tempForm.selectData = []
    }
    form.effect_type = val;
  }
  
  const submitAppConfig = async () => {
    if (!form.title) {
      return ElMessage.error("请填写配置名称");
    }
    if (!form.title) {
      return ElMessage.error("请填写通知标题");
    }
    if (!form.trigger_node) {
      return ElMessage.error("请选择触发节点");
    }
    if (!form.content) {
      return ElMessage.error("请填写通知内容");
    }
    if (form.effect_type === '') {
      return ElMessage.error("请选择生效时间");
    }
    if (isEmpty(form.country_code)) {
      return ElMessage.error("请指定国家");
    } 
    // if (isEmpty(form.effect_role)) {
    //   return ElMessage.error("请指定账号角色");
    // }
    
    if (form.country_code.length === countryList.value.length) {
        form.country_code = -1;
    }
   
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    let res = null;
    if (isEdit.value) {
      res = await editConfig(form)
    } else {
      res = await addConfig(form)
    }
    loading.close()
    if (res.code === 1000) {
      ElMessage.success("提交成功")
      disabled.value = true;
      setTimeout(() => {
        router.go(-1)
      }, 1000);
    } else {
      ElMessage.error(res.message ? res.message : "提交失败")
    }
  }
  
  // life cycle
  
  onMounted(async () => {
    effectTypeList.value = [{"type": 1, "title": "长期"}, {"type": 0, "title": "自定义"}];
    if (!isEmpty(commonStore.appNotifyConfigEnum)) {
        triggerNodeList.value = commonStore.appNotifyConfigEnum.trigger_node;
        // roleList.value = commonStore.appNotifyConfigEnum.role;
        countryList.value = countryList.value.concat(commonStore.appNotifyConfigEnum.country);
    } else {
      const appNotifyConfigRes = await getConfigEnum()
      if (appNotifyConfigRes.code === 1000) {
        // roleList.value = appNotifyConfigRes.data.role;
        triggerNodeList.value = appNotifyConfigRes.data.trigger_node;
        countryList.value = countryList.value.concat(appNotifyConfigRes.data.country);
        commonStore.appNotifyConfigEnum = appNotifyConfigRes.data;
      }
     
    }
  
    if (route.query.id && !isEmpty(commonStore.appNotifyConfigItem)) {
      isEdit.value = true;
      // 因为form是reactive的，不能直接赋值，否则会丢失响应性
      Object.assign(form, commonStore.appNotifyConfigItem,
        {
          country_code: commonStore.appNotifyConfigItem.country_code.split(',')
        })

        if (commonStore.appNotifyConfigItem.country_code == -1) {
            checkAll.value = true;
            form.country_code = countryList.value.map(it => it.id)
        }

        if (commonStore.appNotifyConfigItem.effect_type == 0) {
            tempForm.selectData = [commonStore.appNotifyConfigItem.effect_start_time, commonStore.appNotifyConfigItem.effect_end_time]
        }
    }
  })
  </script>
  
  <style lang="less" scoped>
  .check-all {
    margin-right: 30px;
  }
  
  .add-video {
    margin: 20px;
  }
  
  .btn-box {
    margin-top: 50px;
  
    :deep(.el-form-item__content) {
      display: flex;
      justify-content: center;
    }
  }
  </style>